package com.customization.api.e9sso.cmd;

import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.portal.web.ToolbarAction;
import com.engine.workflow.biz.freeNode.FreeNodeBiz;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
//import com.engine.workflow.entity.publicApi.WorkflowDetailTableInfoEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import okhttp3.*;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.webservices.WorkflowRequestTableField;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

public class RejectCmd extends AbstractCommonCommand<Map<String,Object>> {

    private HttpServletRequest request=null;
    public RejectCmd(User user, HttpServletRequest request) {
        this.user = user;
        this.params = ParamUtil.request2Map(request);
        this.request=request;



        String  str="";
        
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String uuid=UUID.randomUUID().toString();
        Console.log(uuid+"输入参数params:"+params.toString());
        Map<String, Object> apidatas = new HashMap<String, Object>();
        apidatas.put("status",true);
        apidatas.put("msg","退回成功!");

        RecordSet rs=new RecordSet();
        String rejectType=Util.null2String(params.get("rejectType"));
        String requestId=Util.null2String(params.get("requestId"));



        String createNodeID=getCreateNodeID(requestId);
        String acquiringNodeID=getAcquiringNodeID(requestId);

        JSONObject otherParams=new JSONObject();
        if(rejectType.equals("4")){// 大退回 SSF退回电子单、退回实物单据，流程退回到发起人，重新审批

            if(createNodeID.equals("")){
                apidatas.put("status",false);
                apidatas.put("msg","退回失败!");
                apidatas.put("errMsg","未获取到发起节点ID");
                return apidatas;
            }
            otherParams.put("RejectToNodeid",createNodeID);
            otherParams.put("isSubmitDirect","0");
            otherParams.put("RejectToType","0");
        }else if(rejectType.equals("3")){//SSF退回电子单、流程退回到发起人，流程提交直接到达SSF
            if(createNodeID.equals("")){
                apidatas.put("status",false);
                apidatas.put("msg","退回失败!");
                apidatas.put("errMsg","未获取到发起节点ID");
                return apidatas;
            }
            otherParams.put("RejectToNodeid",createNodeID);
            otherParams.put("isSubmitDirect","1");
            otherParams.put("RejectToType","0");

        }else if(rejectType.equals("2")){//退回实物单据 流程退回到影像系统(收单人) 提交到SSF

            if(acquiringNodeID.equals("")){
                apidatas.put("status",false);
                apidatas.put("msg","退回失败!");
                apidatas.put("errMsg","未获取到收单岗节点ID");
                return apidatas;
            }

            otherParams.put("RejectToNodeid",acquiringNodeID);
            otherParams.put("isSubmitDirect","1");
            otherParams.put("RejectToType","0");

        }else if(rejectType.equals("1")){//补齐  流程退回到影像系统(收单人) 提交到SSF

            if(acquiringNodeID.equals("")){
                apidatas.put("status",false);
                apidatas.put("msg","退回失败!");
                apidatas.put("errMsg","未获取到收单岗节点ID");
                Console.log(uuid+"返回值:"+apidatas.toString());
                return apidatas;
            }


            otherParams.put("RejectToNodeid",acquiringNodeID);
            otherParams.put("isSubmitDirect","1");
            otherParams.put("RejectToType","0");
        }

        if(otherParams.size()>1) {
            this.params.put("otherParams", otherParams);
        }

        RecordSet rst=new RecordSet();
        rst.execute("select  workflowid from workflow_requestbase where  requestid='"+requestId+"'");
        if(rst.next()){
           String wfid= ","+rst.getString("workflowid")+",";
           String exports_workflowid=","+Util.null2String(rs.getPropValue("angel_fna","exports_workflowid"))+ ",";
           if(exports_workflowid.contains(wfid)) {
               this.params.remove("otherParams");
           }
        }
        //退回流程
        WorkflowRequestOperatePA workflowRequestOperatePA = new WorkflowRequestOperatePAImpl();
        PAResponseEntity paResponseEntity = workflowRequestOperatePA.rejectRequest(this.user, request2Entity());
        JSONObject  result=JSONObject.parseObject(JSONObject.toJSONString(paResponseEntity));
         String code= Util.null2String(result.get("code"));
         if(!code.equals("SUCCESS")){
             apidatas.put("status",false);
             apidatas.put("msg","退回失败!");
             apidatas.put("errMsg",Util.null2String(result.get("errMsg")));
             apidatas.put("code",code);
             Console.log(uuid+"返回值:"+apidatas.toString());
             return apidatas;
         }






        Console.log(uuid+"返回值:"+apidatas.toString());
        return apidatas;
    }



    private boolean pushStatusYx(int typeid,String title, String context, String linkUrl, String linkMobileUrl, Set<String> userIdList,int creator) {
        MessageType messageType = MessageType.newInstance(typeid); // 消息来源（见文档第四点补充）
        try {
            MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl,
                    linkMobileUrl);
            messageBean.setCreater(creator);// 创建人id
            return Util_Message.store(messageBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


    public static String getCreateNodeID(String requestid){
        RecordSet rs= new RecordSet();
        if(requestid.equals("")){
            return "";
        }
        rs.execute("select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where workflow_flownode.nodeid=workflow_nodebase.id and nodetype=0 and workflow_requestbase.workflowid=workflow_flownode.workflowid and workflow_requestbase.requestid='"+requestid+"'");
        rs.first();

        return rs.getString("nodeid");
    }

    //获取收单节点的节点ID
    public static String getAcquiringNodeID(String requestid){
        RecordSet rs= new RecordSet();
        if(requestid.equals("")){
            return "";
        }
        rs.execute("select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where workflow_flownode.nodeid=workflow_nodebase.id   and  workflow_requestbase.workflowid=workflow_flownode.workflowid and workflow_requestbase.requestid='"+requestid+"' and  workflow_nodebase.NODENAME like '%收单%'");
        rs.first();
        return rs.getString("nodeid");
    }




    public ReqOperateRequestEntity request2Entity() {
        ReqOperateRequestEntity var1 = new ReqOperateRequestEntity();

        try {
            int var2 = Util.getIntValue(Util.null2String(this.params.get("workflowId")));
            int var3 = Util.getIntValue(Util.null2String(this.params.get("requestId")));
            String var4 = Util.null2String(this.params.get("requestName"));
            int var5 = Util.getIntValue(Util.null2String(this.params.get("userId")));
            int var6 = Util.getIntValue(Util.null2String(this.params.get("forwardFlag")));
            String var7 = Util.null2String(this.params.get("forwardResourceIds"));
            String var8 = Util.null2String(this.params.get("mainData"));
            if (!"".equals(var8)) {
                try {
                    List var9 = JSONObject.parseArray(var8, WorkflowRequestTableField.class);
                    var1.setMainData(var9);
                } catch (Exception var16) {
                    var16.printStackTrace();
                }
            }

            String var18 = Util.null2String(this.params.get("detailData"));
            if (!"".equals(var18)) {
                try {
               //     List var10 = JSONObject.parseArray(var18, WorkflowDetailTableInfoEntity.class);
                 //   var1.setDetailData(var10);
                } catch (Exception var15) {
                    var15.printStackTrace();
                }
            }

            String var19 = Util.null2String(this.params.get("remark"));
            String var11 = Util.null2String(this.params.get("requestLevel"));
            String var12 = Util.null2String(this.params.get("otherParams"));
            if (!"".equals(var12)) {
                try {
                    Map var13 = (Map)JSONObject.parseObject(var12, Map.class);
                    var1.setOtherParams(var13);
                } catch (Exception var14) {
                    var14.printStackTrace();
                }
            }
            Console.log("OtherParams:"+var1.getOtherParams().toString());

            var1.setWorkflowId(var2);
            var1.setRequestId(var3);
            var1.setRequestName(var4);
            var1.setUserId(var5);
            var1.setRemark(var19);
            var1.setRequestLevel(var11);
            var1.setForwardFlag(var6);
            var1.setForwardResourceIds(var7);
            var1.setClientIp(Util.null2String(this.params.get("param_ip")));
            int var20 = Util.getIntValue(Util.null2String(this.params.get("submitNodeId")));
            if (var20 > 0 || FreeNodeBiz.isFreeNode(var20)) {
                var1.setSubmitNodeId(var20);
                var1.setEnableIntervenor("1".equals(Util.null2s(Util.null2String(this.params.get("enableIntervenor")), "1")));
                var1.setSignType(Util.getIntValue(Util.null2String(this.params.get("SignType")), 0));
                var1.setIntervenorid(Util.null2String(this.params.get("Intervenorid")));
            }
        } catch (Exception var17) {
            var17.printStackTrace();

        }

        return var1;
    }
}
